#-*- coding: UTF-8 -*-

from pymongo import MongoClient

c = MongoClient()
db = c.inventory
collection = db.items

#定义数据
item = {"Type":"Laptop",
        "ItemNumber" : "1234EXD",
        "Status":"In use",
        "Location":{
            "Department":"Development",
            "Building":"2B",
            "Desk":120101,
            "Owner":"Anderson,Thomas"
        },
        "Tags":["Laptop","Development","In Use"]
        }

#插入一条数据
#collection.insert(item)

#搜索单个文档
#print(collection.find_one())
#print(collection.find_one({"ItemNumber" : "1234EXD"}))

#搜索多个文档
#for doc in collection.find({'Status' : 'In use'},projection={'ItemNumber':True,'Location.Owner':True}):
#    print(doc)

#使用sort(),limit()和skip()简化查询
for doc in collection.find({'Status':'In use'},
projection={'ItemNumber':True,'Location.Owner':True}).sort('ItemNumber'):
    print(doc)

for doc in collection.find({},{"ItemNumber" : "true"}).limit(2):
    print(doc)

for doc in collection.find({},{"ItemNumber" : "true"}).skip(2):
    print(doc)

#聚集查询
#使用count统计
print(collection.count())

#使用distinct()统计唯一数据的数目
print(collection.distinct("ItemNumber"))

#使用聚集框架对数据分组
from bson.son import SON
aggregate = collection.aggregate([
    {'$unwind' : '$Status'},
    {'$group' :{'_id' : '$Status','Totals':{'$sum' :1}}},
    {'$sort' : SON([('Totals',-1)])}
])

#使用hint()指定索引
from pymongo import ASCENDING
print(collection.create_index([("ItemNumber",ASCENDING)]))

for doc in collection.find({"Location.Owner" : "Anderson,Thomas"}).hint([("ItemNumber",ASCENDING)]):
    print(doc)

#使用$lt,$gt,$lte和$gte操作符
for doc in collection.find({"Location.Desk" : {"$lt" : 120102}}):
    print(doc)

for doc in collection.find({"Location.Desk" : {"$gt" : 120102}}):
    print(doc)

for doc in collection.find({"Location.Desk" : {"$lte" : 120102}}):
    print(doc)

for doc in collection.find({"Location.Desk" : {"$gte" : 120102}}):
    print(doc)

#s使用$ne搜索不匹配的数据
print(collection.find({"Status" : {"$ne" : "In use"}}).count())

#使用$in指定匹配的数组
for doc in collection.find({"Tags" : {"$in" : ["Not used","Development"]}},projection={"ItemNumber" : "true"}).limit(2):
    print(doc)

#使用$nin指定不匹配的数组
for doc in collection.find({"Tags":{"$nin" : ["Development"]}},projection={"ItemNumber" : "true"}):
    print(doc)

#搜索匹配数组值的文档
for doc in collection.find({"Tags":{"$all" : ["Storage","Not used"]}},projection={"ItemNumber" : "true"}):
    print(doc)

#使用$or指定多个匹配表达式
for doc in collection.find({"$or" : [{"Location.Department":"Storage"},{"Location.Owner" : "Anderson,Thomas"}]}):
    print(doc)

#使用$slice从数组中获取元素
chair = ({
    "Status" : "Not used",
    "Tags" : ["Chair","Not used","Storage"],
    "ItemNumver" : "6789SID",
    "Location" : {
        "Department" : "Storage",
        "Building" : "2B"
    },
    "PreviousLocation" :
    [ "120100","120101","120102","120103","120104","120105","120106","120107","120108","120109","120110"]
})
collection.insert(chair)